#!/bin/sh
port=3000
project_name="chat"

if [ x$1 = "x" -o y$2 = "y" ];
then
    echo "********************************************************************************************"
    echo "Error: Please enter the environment name and instance count in the argument like: st, uat, sim, prod, ect."
    echo "Example:"
    echo "./start.sh prod 1"
    echo "********************************************************************************************"
	exit 1
fi

echo "********************************************************************************************"

echo "Inputs - Environment [$1] - Instance Count [$2]"

mkdir -p ../logs

for((i=0;i<$2;i++))
{
    echo "Starting $project_name instance [$(( i + 1))] for [$1] environment at port [$port]..."
    outfile="../logs/process_$((i + 1))/process.log"
    if [ -f $outfile ];
    then
        rm $outfile
    fi
    mkdir -p ../logs/process_$((i + 1)) && touch $outfile
    java -jar $project_name.jar --server.port=$port --logging.path=../logs/process_$((i + 1)) --spring.config.location=file:../env/im_config_$1.yml >> $outfile 2>&1 &
    ((port = port + 1))
}

for((i=0;i<10;i++))
{
    echo -ne "."
    sleep 2
}

cat ../logs/process_*/process.log

ps -fu $USER | grep -w $project_name | grep -v grep |awk '{print "Running Service - PID ["$2"] - Start Time ["$5"] - ["$11"] - ["$12"]"}'

serviceCount=($(ps -fu $USER | grep -w "$project_name" | grep -v grep | wc -l))
echo "Total service count [$serviceCount]"

#file="application.pid"

#if [ -f "$file" ];
#then
#    pid=$(cat $file);
#    if [ x$pid = "x" ];
#    then
#        echo "Warn: Process can not be started in the specified duration, please check the logs for start up status"
#    else
#        echo "Process started successfully -  pid [$pid]"
#    fi
#else
	#echo "Warn: Process can not be started in the specified duration, please check the logs for start up status"
#fi
echo "********************************************************************************************"
